package com.jmb.api.common.utils;

import com.jmb.api.common.exception.WebApiException;
import com.jmb.api.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

import static com.jmb.api.common.utils.LoginConstants.tokenExpiration;

public class JwtUtil {
    // token过期时间

    // // 密钥
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    /**
     * 创建token
     * @param userId 用户id
     * @param username 用户名
     * @return
     */
    public static String createToken(Long userId,String username){
        String token = Jwts.builder()
                .setSubject("USER_INFO")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(tokenSignKey)
                .compact();
        return token;
    }

    /**
     * 解析token
     * @param token 解析的token
     * @return
     */
    public static Claims parseToken(String token){
        if (token == null){
            throw new WebApiException(ResultCodeEnum.web_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder()
                    .setSigningKey(tokenSignKey)
                    .build();
            return jwtParser.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            throw new WebApiException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new WebApiException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}
